package cim2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.googlecode.fannj.Fann;
import com.googlecode.fannj.Layer;
import com.googlecode.fannj.Trainer;
import com.googlecode.fannj.TrainingAlgorithm;

public class TrainNet {
	
	private Config cfg;
	
	public TrainNet(Config cfg){
		this.cfg = cfg;
	}
	
	public void test() {		
		try {
	        File temp = File.createTempFile("fannj_", ".tmp");
	        temp.deleteOnExit();        
	        System.out.println("Cargando archivo de datos " + cfg.getDataFile());
	        IOUtils.copy(new FileInputStream("./data/" + cfg.getDataFile()), new FileOutputStream(temp));
	        
	        for (RedParam r : cfg.getRedes()){
	        	System.out.println("Entrenando red: " + r.getNombre());
	        	
	        	List<Layer> layers = r.getCapas();		
		        Fann fann = new Fann(layers);
		        Trainer trainer = new Trainer(fann);
		        //trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_INCREMENTAL);
		        
		        float desiredError = .001f;
		        float mse = trainer.train(temp.getPath(), r.getCiclos(), r.getImprimirCada(), desiredError);
		        
		        System.out.println("Error de la red: " + mse + " --- Error de referencia: " + desiredError);
		        //assertTrue("" + mse, mse <= desiredError);
		        
		        String netFile = cfg.getDataFile() + "." + r.getNombre() + ".net";
		        System.out.println("Guardando red entrenada en " + netFile);
		        fann.save("./results/" + netFile);      
	        }
	        
		} catch (Exception e){
			e.printStackTrace();
		}		
	}
}
